// pages/record/index.js
const app = new getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: '2019-1-1',
    endTime: '2019-1-1',
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate(),
    isSet: false,
    today: true,
    isToday: true,
    comeText: '大姨妈来咯',
    comeUrl: '/image/water.png',
    days_style: [
      // { month: 'current', day: 28, color: 'white', background: 'rgba(252, 88, 113, 0.4)' },
      // { month: 'current', day: 29, color: 'white', background: 'rgba(252, 88, 113, 0.4)' },
      // { month: 'current', day: 30, color: 'white', background: 'rgba(252, 88, 113, 0.4)' },
      // { month: 'current', day: 31, color: 'white', background: 'rgba(252, 88, 113, 0.4)' },
      { month: 'current', day: new Date().getDate(), color: 'white', background: 'rgb(255,215,0)' },
      { month: 'current', day: 0, color: 'white', background: 'rgb(0,255,0)' },
    ],
    forecastDate: [],        //预测的日期
    forecastPeriod: [],      //预测经期哪几天
    period_style: [],        //经期预测在日历的样式
    coming_style: [],        //经期来了的样式
    switch1Status: false,
    switch1Status: false,
    isComing: false,
    isPregnant: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options);
    // console.log(new Date().getFullYear(),new Date().getMonth() + 1, new Date().getDate());
    // 设置一下大姨妈来了的按钮的日期
    var curMonth = new Date().getMonth() + 1;
    var date = new Date().getFullYear() + '-' + curMonth + '-' + new Date().getDate();
    this.setData({
      date: date,
      endTime: date
    });
    // 判断是否设置经期
    app.userInfoReadyCallback = res => {
      console.log(res);
      if (res != '') {
        console.log(app.globalData.openid);
        this.isPeriod();
        var curMonth = new Date().getMonth() + 1;
        var curDate = new Date().getFullYear() + '-' + curMonth;
        // console.log(curDate);
        this.forecastPeriod(curDate, 0, '');
        // this.isPeriodRecord(new Date().getFullYear() + '-' + new Date().getMonth() + 1, 0);
        this.btnRecordstatus();
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  switch1Change: function (e) {
    // console.log('switch1 发生 change 事件，携带值为', e.detail.value);
    if (e.detail.value) {
      this.setData({
        comeText: '大姨妈走啦',
        comeUrl: '/image/stop.png',
        switch1Status: e.detail.value
      });
      wx.showToast({
        title: '请选择月经开始的日期',
        icon: 'none',
        duration: 2600
      });

    } else {
      this.setData({
        comeText: '大姨妈来咯',
        comeUrl: '/image/water.png',
        switch1Status: e.detail.value
      });
      wx.showToast({
        title: '请选择月经结束的日期',
        icon: 'none',
        duration: 2600
      });
    }
  },
  // 大姨妈来咯按钮的日期选择确认按钮
  bindDateChange: function (e) {
    // console.log(e);
    // console.log(this.data.switch1Status);
    var date = e.detail.value;
    if (this.data.switch1Status) {
      this.setData({
        isComing: true
      });
      this.periodRecord(date, 1);
    } else {
      this.setData({
        isComing: false
      });
      this.periodRecord(date, 0);
    }
  },
  // 大姨妈来咯按钮的日期选择取消按钮
  bindcancel: function (e) {
    // console.log(e);
    // console.log(this.data.switch1Status);
    if (this.data.switch1Status) {
      this.setData({
        comeText: '大姨妈来咯',
        comeUrl: '/image/water.png',
        isComing: false
      });
    } else {
      this.setData({
        comeText: '大姨妈走啦',
        comeUrl: '/image/stop.png',
        isComing: true
      });
    }
  },
  switch2Change: function (e) {
    // console.log(e);
    // console.log('switch2 发生 change 事件，携带值为', e.detail.value)
  },
  // 日历控件上一个月
  prev: function (e) {
    // console.log(e);
    var that = this;
    // 修改当前月份的样式
    this.curMonthStyle(e);
    // 经期预测
    var nowDate = new Date().getMonth() + 1;
    var nowMonth = new Date().getFullYear() + '-' + nowDate;
    var curMonth = e.detail.currentYear + '-' + e.detail.currentMonth;
    var prevMonth = e.detail.prevYear + '-' + e.detail.prevMonth;
    var beforePeriod = this.data.forecastDate[0];
    wx.request({
      url: app.globalData.serverUrl + 'compareMonth',
      method: 'GET',
      data: {
        nowMonth: nowMonth,
        curMonth: curMonth
      },
      success: function (e) {
        // console.log(e);
        if (e.data.status == 0) {
          // that.isPeriodRecord(new Date().getFullYear() + '-' + new Date().getMonth() + 1,0);
          that.forecastPeriod(nowMonth, 0, '');
        } else if (e.data.status == 1) {
          // 清除经期的样式
          // that.isPeriodRecord(curMonth,1);
          that.forecastPeriod(prevMonth, 2, beforePeriod);
        } else {
          that.isPeriodRecord(curMonth, 1);
        }
      }
    })
    // var beforePeriod = this.data.forecastDate[0];
    // this.forecastPeriod(prevMonth, 2, beforePeriod);
  },
  // 日历控件下一个月
  next: function (e) {
    // console.log(e);
    var that = this;
    // 修改当前月份的样式
    this.curMonthStyle(e);
    // 经期预测
    var nowDate = new Date().getMonth() + 1;
    var nowMonth = new Date().getFullYear() + '-' + nowDate;
    // console.log(nowMonth);
    var curMonth = e.detail.currentYear + '-' + e.detail.currentMonth;
    var beforePeriod = this.data.forecastDate[this.data.forecastDate.length - 1];
    wx.request({
      url: app.globalData.serverUrl + 'compareMonth',
      method: 'GET',
      data: {
        nowMonth: nowMonth,
        curMonth: curMonth
      },
      success: function (e) {
        // console.log(e);
        if (e.data.status == 0) {
          // 等于本月的时候
          // that.isPeriodRecord(new Date().getFullYear() + '-' + new Date().getMonth() + 1,0);
          that.forecastPeriod(nowMonth, 0, '');
        } else if (e.data.status == 1) {
          // 大于本月预测经期
          that.forecastPeriod(curMonth, 1, beforePeriod);
        } else {
          // 小于本月查询经期记录
          that.isPeriodRecord(curMonth, 1);
        }
      }
    })
    // var beforePeriod = this.data.forecastDate[this.data.forecastDate.length-1];
    // this.forecastPeriod(curMonth, 1, beforePeriod);
  },
  // 顶部日期改变
  // dateChange:function(e){
  //   // console.log(e);
  //   this.curMonthStyle(e);
  // },
  // 点击日期
  dayClick: function (e) {
    // console.log(e);
    // 点击的设置样式
    var len = this.data.days_style.length - 1;
    var day = 'days_style[' + len + '].day';
    // var color = 'days_style['+ len +'].color';
    // var bg = 'days_style['+ len +'].background';
    var isShow = false;
    // console.log(this.data.year, this.data.month);
    // 判断是否当日
    if ((e.detail.year == this.data.year) && (e.detail.month == this.data.month) && (e.detail.day == this.data.day)) {
      isShow = true;
    }
    this.setData({
      today: isShow,
      isToday: isShow,
      [day]: e.detail.day,
      // [color]: 'white',
      // [bg]: 'rgb(0,255,0)'
    });
  },
  // 设置当前月份日期的样式
  curMonthStyle: function (e) {
    // console.log(this.data.days_style.length);
    var len = this.data.days_style.length - 2;
    // var color = 'days_style['+ len +'].color';
    // var bg = 'days_style['+ len +'].background';
    var day = 'days_style[' + len + '].day';
    // console.log(color,bg);
    if ((e.detail.currentYear == new Date().getFullYear()) && (e.detail.currentMonth == new Date().getMonth() + 1)) {
      this.setData({
        [day]: new Date().getDate(),
        today: true,
        isToday: true
        // [color]:'white',
        // [bg]:'rgb(255,215,0)'
      });
    } else {
      this.setData({
        // [color]: '#4a4f74',
        // [bg]: 'white'
        [day]: 0,
        today: false,
        isToday: false,
      });
    }
  },
  // 返回今天
  backToday: function () {
    var len = this.data.days_style.length - 2;
    // var color = 'days_style['+ len +'].color';
    // var bg = 'days_style['+ len +'].background';
    var day = 'days_style[' + len + '].day';
    var len1 = this.data.days_style.length - 1;
    var day1 = 'days_style[' + len1 + '].day';
    this.setData({
      year: this.data.year,
      month: this.data.month,
      today: true,
      isToday: true,
      // [color]: 'white',
      // [bg]: 'rgb(255,215,0)',
      [day]: new Date().getDate(),
      [day1]: 0,
    });
    // this.isPeriodRecord(new Date().getFullYear() + '-' + new Date().getMonth() + 1,0);
    var curMonth = new Date().getMonth() + 1;
    this.forecastPeriod(new Date().getFullYear() + '-' + curMonth, 0, '');
  },
  // 判断是否设置经期
  isPeriod: function () {
    var that = this;
    wx.request({
      url: app.globalData.serverUrl + 'isperiod',
      method: 'GET',
      data: {
        openid: app.globalData.openid
      },
      success: function (e) {
        //  console.log(e);
        if (e.data.status == 0) {
          that.setData({
            isSet: false
          });
        } else {
          that.setData({
            isSet: true
          });
        }
      }
    })
  },
  // 经期设置
  periodSetting: function () {
    // console.log('经期设置');
    wx.request({
      url: app.globalData.serverUrl + 'isRegister',
      method: 'GET',
      data: {
        openid: app.globalData.openid
      },
      success: function (e) {
        // console.log(e);
        if (e.data.status == 1) {
          wx.navigateTo({
            url: '/pages/me/periodsetting?fisrt=1'
          })
        } else {
          wx.showToast({
            title: '请先登录',
            icon: 'loading',
            duration: 800,
            success: function (res) {
              setTimeout(function () {
                wx.switchTab({
                  url: '/pages/me/index'
                })
              }, 800);
            }
          })
        }
      }
    })
  },
  // 月经预测
  forecastPeriod: function (curMonth, type, beforePeriod) {
    // console.log(curMonth,type,beforePeriod);
    var that = this;
    wx.request({
      url: app.globalData.serverUrl + 'forecastPeriod',
      method: 'GET',
      data: {
        openid: app.globalData.openid,
        curMonth: curMonth,
        type: type,
        beforePeriod: beforePeriod
      },
      success: function (e) {
        // console.log(e);
        if (e.data.forecastPeriod) {
          // 清空原来的预测日期、经期日期
          // console.log(that.data.days_style.length);
          if (that.data.days_style.length > 2) {
            var len = that.data.days_style.length - 2;
            that.data.days_style.splice(0, len);
          }
          var showPeriod = [];                        //要添加到days_style里面的元素
          var period_day_style = [];                  //经期预测的样式
          var len = e.data.forecastPeriod.length;     //获取要循环便利经期数组的长度
          // console.log(e.data.forecastPeriod);
          for (var i = 0; i < len; i++) {
            var addPeriod = { month: 'current', day: e.data.forecastPeriod[i], color: 'white', background: 'rgba(252, 88, 113, 0.4)' };
            showPeriod.push(addPeriod);               //把预测的经期样式加到要展示的数组里面
            period_day_style.push(addPeriod);
          }
          // console.log(showPeriod);
          console.log(period_day_style);

          // 把今天和点击天的样式加进去
          showPeriod.push(that.data.days_style[0]);
          showPeriod.push(that.data.days_style[1]);
          // console.log(showPeriod);
          that.setData({
            forecastDate: e.data.forecastDate,
            forecastPeriod: e.data.forecastPeriod,
            days_style: showPeriod,
            period_style: period_day_style,
          });
          // console.log(that.data.period_style);
          // 如果是当前月判断是否有经期记录
          if (type == 0) {
            var curMonth = new Date().getMonth() + 1;
            that.isPeriodRecord(new Date().getFullYear() + '-' + curMonth, 0);
          }
        }
      }
    })
  },
  // 插入或者删除经期记录
  periodRecord: function (date, status) {
    var that = this;
    wx.request({
      url: app.globalData.serverUrl + 'periodRecord',
      method: 'GET',
      data: {
        openid: app.globalData.openid,
        date: date,
        status: status
      },
      success: function (e) {
        // console.log(e);
        if (e.data) {
          if (e.data.status == 1) {
            // 展示一下经期记录
            // that.isPeriodRecord(new Date().getFullYear() + '-' + new Date().getMonth() + 1,0);
            var curMonth = new Date().getMonth() + 1;
            // 重新预测一下经期
            that.forecastPeriod(new Date().getFullYear() + '-' + curMonth, 0, '');
          }
        }
      }
    })
  },
  // 查询本月是否有经期记录
  // status = 0 本月 1小于本月
  isPeriodRecord: function (curMonth, status) {
    var that = this;
    wx.request({
      url: app.globalData.serverUrl + 'isPeriodRecord',
      method: 'GET',
      data: {
        openid: app.globalData.openid,
        curMonth: curMonth
      },
      success: function (e) {
        // console.log(e);
        // 清空原来的预测日期
        // console.log(that.data.period_style);
        if (that.data.days_style.length > 2) {
          var len = that.data.days_style.length - 2;
          that.data.days_style.splice(0, len);
        }
        if (e.data) {
          var period_style = [];
          if (status == 0) {
            period_style = that.data.period_style;    //如果在本月的时候经期预测的显示样式
          }
          var len1 = e.data.length;
          var coming_style = [];                        //经期来的时候的样式
          if (len1 > 0) {
            for (var i = 0; i < len1; i++) {
              var addDay = { month: 'current', day: e.data[i], color: 'white', background: 'rgb(252, 88, 113)' };
              period_style.push(addDay);
              coming_style.push(addDay);
            }
            // 把今天和点击天的样式加进去
            period_style.push(that.data.days_style[0]);
            period_style.push(that.data.days_style[1]);
            // console.log(period_style);
            // console.log(coming_style);
            that.setData({
              days_style: period_style,
              coming_style: coming_style
            });
          }
        } else {
          // console.log(e);
          var arr_period_style = [];    //经期预测的显示样式
          if (status == 0) {
            arr_period_style = that.data.period_style;    //如果在本月的时候经期预测的显示样式
          }
          // 把今天和点击天的样式加进去
          arr_period_style.push(that.data.days_style[0]);
          arr_period_style.push(that.data.days_style[1]);
          that.setData({
            days_style: arr_period_style
          });
        }
      }
    })
  },
  // 判断一下两个按钮的值
  btnRecordstatus: function () {
    var that = this;
    wx.request({
      url: app.globalData.serverUrl + 'btnRecordStatus',
      method: 'GET',
      data: {
        openid: app.globalData.openid
      },
      success: function (e) {
        // console.log(e);
        if (e.data) {
          var isComing = false;
          var isPregnant = false;
          if (e.data.isEnd == 0) {
            isComing = true;
          }
          if (e.data.isPregnant == 1) {
            isPregnant = true;
          }
          if (isComing) {
            that.setData({
              isComing: isComing,
              isPregnant: isPregnant,
              comeText: '大姨妈走啦',
              comeUrl: '/image/stop.png',
            });
          } else {
            that.setData({
              isComing: isComing,
              isPregnant: isPregnant,
              comeText: '大姨妈来咯',
              comeUrl: '/image/water.png',
            });
          }
        }
      }
    })
  }
})